// import { ftCreate, ftUpdate } from '@/service/modules/tag';
import { Form, Input, message, Modal } from 'antd';
import { forwardRef, memo, useEffect, useImperativeHandle } from 'react';
import { useModel } from 'umi';

type Iprops = {
  onClose: (refresh?: boolean) => void;
  open: boolean;
  title: string;
  data: any;
};
type FormValues = {
  id?: string;
  text: string;
  user_id: number;
};

export interface IAddOrUpdateRef {
  init: () => void;
}

const AddOrUpdate = (props: Iprops, ref: React.Ref<IAddOrUpdateRef>) => {
  const { onClose, open, title, data } = props;
  const [form] = Form.useForm<FormValues>();
  const { createAction, updateAction } = useModel('tagModel');

  async function onOk() {
    // 检查form数据
    await form.validateFields();

    const from = form.getFieldsValue(['id', 'text', 'user_id']);

    const { id, text, user_id } = from;
    let res = null;
    if (!id) {
      res = await createAction(
        {
          text,
          userId: 1,
        },
        true,
      );
    } else {
      res = await updateAction(
        {
          id,
          text,
          userId: 1,
        },
        true,
      );
    }
    const { code, message: msg } = res;
    if (code === 200) {
      message.success('操作成功');
      onCancel();
    } else {
      message.error(`操作失败: ${msg}`);
    }
  }
  function onCancel() {
    form.resetFields();
    onClose();
  }

  useEffect(() => {
    if (!data) return;
    const { id, text, user_id } = data;
    form.setFieldsValue({
      id,
      text,
      user_id,
    });
  }, [data]);

  useImperativeHandle(ref, () => {
    return {
      init() {
        console.log('use的方法被使用');
      },
    };
  });

  return (
    <Modal
      title={title}
      closable={{ 'aria-label': 'Custom Close Button' }}
      open={open}
      onOk={onOk}
      onCancel={onCancel}
    >
      <Form form={form} name="demo_form" layout="vertical">
        <Form.Item label="标签" name="text" rules={[{ required: true, message: '请输入标签!' }]}>
          <Input placeholder="请输入标签" />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default memo(forwardRef(AddOrUpdate));
